require "json"
require "router"
require "http/params"
require "./sms/*"

class WebServer
  include Router

  def draw_routes

    post "/send" do |context, params|
      body = context.request.body.not_nil!.gets_to_end

      if body
        params = JSON.parse body
        mobile = params["mobile"].to_s
        ret_code = 0
        message = ""

        flag, msg = Store.can?(mobile)
        if flag
          code = Util.verify_code
          # f, m = Sender.send(mobile, code)
          f, m = 1, code
          if f == 1
            Store.save(mobile, code)
            ret_code = 1
          end
          message = m
        else
          message = msg
        end

        ret_json = {code: ret_code, message: message}.to_json
        context.response.print ret_json
      else
        ret_json = {code: 0, message: "No params"}.to_json
        context.response.print ret_json
      end
      context
    end

    get "/check" do |context, params|
      params = context.request.query_params
      code, msg = Store.check(params["mobile"].to_s, params["code"].to_s)
      ret_json = {code: code, message: msg}.to_json
      context.response.print ret_json
      context
    end
  end

  def run
    server = HTTP::Server.new([
      HTTP::LogHandler.new,
      HTTP::CompressHandler.new,
      route_handler])
    server.bind_tcp 4000
    server.listen
  end
end

web_server = WebServer.new
web_server.draw_routes
web_server.run
